/* eslint-disable no-undef */
import { OrderType } from '@/enums'
import {
  deleteOrder,
  followOrUnfollow,
  getPrescriptionInfo,
  orderCancel
} from '@/services/consult'
import { sendMobileCode } from '@/services/user'
import type { ConsultOrderItem, followType } from '@/types/consult'
import type { sendType } from '@/types/user'
import {
  showFailToast,
  showImagePreview,
  showSuccessToast,
  type FormInstance
} from 'vant'
// 这个模块放置的是 组合式API的逻辑复用的函数 习惯Hook函数
export const useFollow = (type: followType) => {
  const loading = ref(false)
  const followDoc = async (item: { id: string; likeFlag: number }) => {
    // 开启loading
    loading.value = true
    try {
      // 携带医生id发送请求
      await followOrUnfollow({ id: item.id, type })
      // 请求成功后视图要更新
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      // 关闭loading
      loading.value = false
    }
  }
  return { loading, followDoc }
}
// 处方预览的hook函数
export const useShowPreInfo = () => {
  // 获取处方信息并预览展示
  const showPreInfo = async (id: string | undefined) => {
    if (!id) return
    const res = await getPrescriptionInfo(id)
    // 预览
    showImagePreview([res.data.url])
  }
  return { showPreInfo }
}

// 取消问诊订单的hook函数
export const useCancelOrder = () => {
  // 取消问诊
  const cancelLoading = ref(false)
  const cancel = async (item: ConsultOrderItem) => {
    try {
      cancelLoading.value = true
      await orderCancel(item.id)
      showSuccessToast('取消成功')
      // 修改状态
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
    } catch {
      showFailToast('取消失败')
    } finally {
      cancelLoading.value = false
    }
  }
  return {
    cancelLoading,
    cancel
  }
}

// 删除订单的hook
export const useDeleteOrder = (cb: () => void) => {
  const deleteLoading = ref(false)
  const deleteOrderItem = async (item: ConsultOrderItem) => {
    deleteLoading.value = true
    try {
      await deleteOrder(item.id)
      showSuccessToast('删除成功')
      // 删除完毕后 ,有的需要回退, 有的需要通知父组件
      cb && cb()
    } catch {
      showFailToast('删除失败')
    } finally {
      deleteLoading.value = false
    }
  }
  return {
    deleteLoading,
    deleteOrderItem
  }
}

// 封装获取验证码的hook函数
export const useGetCode = (mobile: Ref<string>, type: sendType) => {
  const formRef = ref<FormInstance>()
  const time = ref(0)
  let timeId = -1
  // 发送验证码
  const sendCode = async () => {
    // 1.校验手机号 (1.form绑定ref 2.调用validate('name属性')方法  3.对应校验的field表单添加name属性 )
    await formRef.value?.validate('mobile')
    // console.log('通过')
    // 2. 获取验证码
    await sendMobileCode(mobile.value, type)
    // 3. 提示
    showSuccessToast('验证码已发送')
    clearInterval(timeId)
    // 4. 开启倒计时
    time.value = 60
    timeId = setInterval(() => {
      time.value--
      if (time.value <= 0) clearInterval(timeId)
    }, 1000)
  }
  // 组件销毁后清除定时器
  onUnmounted(() => {
    clearInterval(timeId)
  })
  return {
    sendCode,
    time,
    formRef
  }
}
